import { ShelfPackage } from '@/api/Shelf';
import { CategoryCascader } from '@/components/CategoryCascader';
import { CoursewaresList } from '@/components/CoursewaresList';
import { SourceSelectModal } from '@/components/SourceSelect';
import Source from '@/components/SourceSelect/Entity/Source';
import { useAppSelector } from '@/redux/store';
import { useRequest } from 'ahooks';
import type { UploadFile } from 'antd';
import { App, Button, Card, Form, Input, Space } from 'antd';
import { useMemo, useState } from 'react';
import { useYmAliOss, YmAddPageLayout, YmUpload, type YmAddPageLayoutProps } from 'ym-design';
import { SelfPackageInfo } from '../interface';

export interface AddEditPorps extends SelfPackageInfo {
  onBack?(): void;
}

type FormValue = {
  coursewares: Source[];
  classType: string[];
  name: string;
  cover?: UploadFile[];
};

const { PaneItem } = YmAddPageLayout;

export function AddEdit({ guid, onBack }: AddEditPorps) {
  const [itemProps] = CategoryCascader.useFieldLevelTwo();
  const [form] = Form.useForm<FormValue>();
  const [modalOpen, setModalOpen] = useState<number>();
  const { entId } = useAppSelector((state) => state.loginEnt);
  // const [defaultValue, setDefaultValue] = useState<DefaultType>();
  const { message } = App.useApp();
  useRequest(
    async () => {
      if (guid) {
        return Source.getSelfPackageDetail(guid);
      }
    },
    {
      ready: Boolean(guid),
      onSuccess(data) {
        if (data) {
          form.setFieldsValue({
            coursewares: data.coursewareList || [],
            classType: [data.parClassId, data.classType],
            name: data.name,
            cover: data.cover ? [{ url: data.cover, uid: data.cover }] : [],
          });
        }
      },
    },
  );

  const { run, loading } = useRequest(ShelfPackage.selfCreate, {
    manual: true,
    onSuccess() {
      onBack?.();
    },
  });

  const customRequest = useYmAliOss();

  // 提交
  const formSub = async () => {
    const { coursewares: _coursewares, cover: _cover, classType: _classType, ...value } = await form.validateFields();
    console.log('_coursewares', _coursewares);
    if (_coursewares) {
      const params = {
        ...value,
        classType: Array.isArray(_classType) ? _classType[1] : _classType,
        entId,
        guid,
        studyType: 100, // 学习类型 类型 100学习 200每日一学 300考试 400AI学习
        parentId: 0, // 课件包只有一层
        courseWareGroupType: 400, // 课件包是400
        studyObject: '', //学习对象
        areaAddress: '',
        areaCode: '',
        coursewareList: _coursewares.map((v, index) => {
          return {
            guid: v.id,
            sourceType: 100, //自建就写死100
            type: v.type === '试卷' ? 200 : 100, //视频图文pdf都传100   试卷传200
            // sortNum: index + 1,
          };
        }),
        cover: _cover?.map((v) => v.response ?? v.url).join(','),
      };
      if (params.coursewareList.length === 0) {
        message.error('请选择课件');
        return;
      } else if (params.coursewareList.length > 20) {
        message.error('课件包最多添加20个课件');
        return;
      }
      run(params);
    } else {
      message.error('请选择课件');
    }
  };

  const operationFooter = useMemo(() => {
    const operationBtn = [
      <Button key="subOnce" type="primary" size="small" onClick={formSub} disabled={loading}>
        保存
      </Button>,
    ];
    return operationBtn;
  }, [loading]);

  const layoutParams: YmAddPageLayoutProps = useMemo(
    () => ({
      leftOperation: {
        onBack: () => {
          onBack?.();
        },
      },
      rightOperationDom: [operationFooter],
      destroyInactiveTabPane: false,
    }),
    [operationFooter],
  );

  return (
    <YmAddPageLayout {...layoutParams}>
      <PaneItem tabKey="tab1" label={guid ? '编辑课件包' : '创建课件包'} className="pane_tab1">
        <div style={{ height: '100%', overflow: 'auto' }}>
          <Form form={form} labelCol={{ style: { width: 100 } }}>
            <Card title="基础信息" style={{ marginBottom: 16 }}>
              <Form.Item label="课件包名称" name="name" rules={[{ required: true }]}>
                <Input showCount autoComplete="off" maxLength={18}></Input>
              </Form.Item>
              <Form.Item label="分类" name="classType" {...itemProps} rules={[{ required: true }]}>
                <CategoryCascader />
              </Form.Item>
              <Form.Item label="封面图">
                <Space size={20}>
                  <Form.Item name="cover" noStyle rules={YmUpload.formRules(false)}>
                    <YmUpload maxCount={1} cardWidth={138} cardHeight={138} customRequest={customRequest}>
                      上传图片
                    </YmUpload>
                  </Form.Item>
                  <div>
                    <p>图片仅支持jpg、png格式 </p>
                    <p> 图片大小750*400 </p>
                  </div>
                </Space>
              </Form.Item>
            </Card>
            <Card
              title="选择课件"
              extra={
                <Button
                  type="primary"
                  shape="round"
                  onClick={() => {
                    setModalOpen(Math.random());
                  }}
                >
                  选择
                </Button>
              }
            >
              <Form.Item name="coursewares" noStyle>
                <SourceSelectModal openDep={modalOpen} preSet="课件"></SourceSelectModal>
              </Form.Item>
              <Form.Item name="coursewares" noStyle>
                <CoursewaresList resourceType="100" />
              </Form.Item>
            </Card>
          </Form>
        </div>
      </PaneItem>
    </YmAddPageLayout>
    // <YmAddPageLayout
    //   title={guid ? '编辑课件包' : '创建课件包'}
    //   onBack={onBack}
    //   items={[
    //     {
    //       text: '保存',
    //       key: 'save',
    //       loading,
    //       onClick: async () => {
    //         const {
    //           coursewares: _coursewares,
    //           cover: _cover,
    //           classType: _classType,
    //           ...value
    //         } = await form.validateFields();
    //         console.log('_coursewares', _coursewares);
    //         if (_coursewares) {
    //           const params = {
    //             ...value,
    //             classType: Array.isArray(_classType) ? _classType[1] : _classType,
    //             entId,
    //             guid,
    //             studyType: 100, // 学习类型 类型 100学习 200每日一学 300考试 400AI学习
    //             parentId: 0, // 课件包只有一层
    //             courseWareGroupType: 400, // 课件包是400
    //             studyObject: '', //学习对象
    //             areaAddress: '',
    //             areaCode: '',
    //             coursewareList: _coursewares.map((v, index) => {
    //               return {
    //                 guid: v.id,
    //                 sourceType: 100, //自建就写死100
    //                 type: v.type === '试卷' ? 200 : 100, //视频图文pdf都传100   试卷传200
    //                 // sortNum: index + 1,
    //               };
    //             }),
    //             cover: _cover?.map((v) => v.response ?? v.url).join(','),
    //           };
    //           if (params.coursewareList.length === 0) {
    //             message.error('请选择课件');
    //             return;
    //           } else if (params.coursewareList.length > 20) {
    //             message.error('课件包最多添加20个课件');
    //             return;
    //           }
    //           run(params);
    //         } else {
    //           message.error('请选择课件');
    //         }
    //       },
    //       style: {
    //         width: 295,
    //       },
    //     },
    //   ]}
    // >
    //   <div style={{ height: '100%', overflow: 'auto' }}>
    //     <Form form={form} labelCol={{ style: { width: 100 } }}>
    //       <Card title="基础信息" style={{ marginBottom: 16 }}>
    //         <Form.Item label="课件包名称" name="name" rules={[{ required: true }]}>
    //           <Input showCount autoComplete="off" maxLength={18}></Input>
    //         </Form.Item>
    //         <Form.Item label="分类" name="classType" {...itemProps} rules={[{ required: true }]}>
    //           <CategoryCascader />
    //         </Form.Item>
    //         <Form.Item label="封面图">
    //           <Space size={20}>
    //             <Form.Item name="cover" noStyle rules={YmUpload.formRules(false)}>
    //               <YmUpload maxCount={1} cardWidth={375} cardHeight={200} customRequest={customRequest}>
    //                 请上传封面
    //               </YmUpload>
    //             </Form.Item>
    //             <div>
    //               <p>图片仅支持jpg、png格式 </p>
    //               <p> 图片大小750*400 </p>
    //             </div>
    //           </Space>
    //         </Form.Item>
    //       </Card>
    //       <Card
    //         title="选择课件"
    //         extra={
    //           <Button
    //             type="primary"
    //             shape="round"
    //             onClick={() => {
    //               setModalOpen(Math.random());
    //             }}
    //           >
    //             选择
    //           </Button>
    //         }
    //       >
    //         <Form.Item name="coursewares" noStyle>
    //           <SourceSelectModal openDep={modalOpen} preSet="课件"></SourceSelectModal>
    //         </Form.Item>
    //         <Form.Item name="coursewares" noStyle>
    //           <CoursewaresList resourceType="100" />
    //         </Form.Item>
    //       </Card>
    //     </Form>
    //   </div>
    // </YmAddPageLayout>
  );
}
